package com.yanzhang.util;

import org.junit.Test;

import java.sql.*;
import java.util.Properties;

/**
 * @author yanzhang
 */
public class DBUtil {
    public static final String driver;
    public static final String url;
    public static final String username;
    public static final String password;

    static {
        Properties properties = PropertiesUtil.getProperties("db.properties");
        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }

    /**
     * @return
     */
    public static Connection getConnection () {
        return getConnection(driver, url, username, password);
    }

    //获取数据库连接
    public static Connection getConnection (String driver, String url, String username, String password) {
        Connection connection = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    //编写查询公共方法
    public static ResultSet query (Connection connection, PreparedStatement preparedStatement, ResultSet rs, String sql, Object[] params) throws SQLException {
        preparedStatement = connection.prepareStatement(sql);
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }
        }
        rs = preparedStatement.executeQuery();
        return rs;
    }

    //编写增删改公共方法
    public static int execute (Connection connection, PreparedStatement preparedStatement, String sql, Object[] params) throws SQLException {
        preparedStatement = connection.prepareStatement(sql);
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }
        }
        return preparedStatement.executeUpdate();
    }

    //释放资源
    public static void closeResource (PreparedStatement preparedStatement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     */
    public static void closeConnection (Connection connection) {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test () {
        Connection connection = DBUtil.getConnection();
        System.out.println(connection);
        DBUtil.closeConnection(connection);
    }
}
